package i_iterator.a_design_pattern;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by wug on 2016/7/13 0013.
 */
public class MainTest {
    public static void main(String[] args) {
        MyArrayList<Item> myArrayList = new MyArrayList<>();
        add(myArrayList);
        System.out.println("-----------使用for循环的遍历----------");
        get(myArrayList);
        /**
         * 现在我们自己实现了 ArrayList
         * 但是我们真的实现了吗？
         *
         * java 原生的ArrayList 可是有迭代器的哦！
         */
        List list = new ArrayList<>();
        Iterator it =  list.iterator();

        System.out.println("--------使用自己的迭代器的迭代-------------");
        /**
         * ok 用迭代器再遍历一次 这就是迭代模式
         */
        myIterator(myArrayList);

        System.out.println("------------使用过滤器的迭代------------------");

        myFilterIterator(myArrayList);

        System.out.println("-----------使用自己的迭代器迭代Map--------------");

        /**
         * 用自己的迭代器迭代map
         */
        MyMap<Item> myMap = new MyMap();
        myMap.put("a", myArrayList.get(0));
        myMap.put("b", myArrayList.get(1));
        mapIterator(myMap);

        /**
         * 使用map的get方法
         */
        Item item = myMap.get("a");
        System.out.println(item.getName());
    }

    private static void add(MyArrayList<Item> myArrayList) {
        for (int i = 0; i < 12; i++) {
            Item item = new Item();
            item.setId(i);
            item.setName("name"+i);
            myArrayList.add(item);
        }
    }

    private static void get(MyArrayList<Item> myArrayList) {
        for (int i = 0; i < myArrayList.size(); i++) {
            System.out.println(myArrayList.get(i).getName());
        }
    }

    private static void myIterator(MyArrayList<Item> myArrayList) {
        MyIterator<Item> myIt = myArrayList.iterator();
        while (myIt.hasNext()) {
            System.out.println(myIt.next().getName());
        }
    }

    private static void myFilterIterator(MyArrayList<Item> myArrayList) {
        MyIterator<Item> myIt = myArrayList.filterIterator();
        while (myIt.hasNext()) {
            System.out.println(myIt.next().getName());
        }
    }

    private static void mapIterator(MyMap<Item> myMap) {
        MyIterator<Item> myIt =  myMap.iterator();
        while (myIt.hasNext()) {
            System.out.println(myIt.next().getName());
        }
    }
}
